<template>
  <el-dialog title="Variants" :visible="true" @close="closeVariantDialog">
    <div class="area">
      <div class="areaLeft">
        <div id="topSearch" class="topSearch">
          <el-row>
            <el-input
              v-model="searchCriteria.name"
              maxlength="50"
              clearable
              placeholder="name"
            />
            <el-button type="primary" @click="searchData()">Search</el-button>
          </el-row>
        </div>
        <el-table :data="tableData" :loading="loading">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <div v-if="scope.row.listLeaf.length > 0" class="tags">
                <el-tag
                  v-for="item in scope.row.listLeaf"
                  :key="item.id"
                  closable
                  @close="deleteItem(item)"
                >{{ item.name }}</el-tag>
              </div>
              <div v-else class="noData">
                no data
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="Name" />
          <el-table-column fixed="right" label="Operation" width="130">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="deleteItem(scope.row)"
              >Delete</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="tableData.length"
          :current-page="currentPage"
          :page-sizes="[10, 30, 50, 100, 200]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="areaRight">
        <p>Add variant</p>
        <el-form v-model="form">
          <el-form-item>
            <el-input v-model="form.name" placeholder="name" />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="form.parentId"
              placeholder="parent"
              :loading="parentLoading"
              @visible-change="getSpecParent"
            >
              <el-option
                v-for="(item, index) in parentOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="text-align:right;">
            <el-button
              v-preventReClick
              type="primary"
              :disabled="!form.name"
              @click="addData"
            >Add</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  productVariantPage,
  productVariantAdd,
  productVariantList,
  productVariantDeleteName,
  productVariantDeleteVal
} from '@/api/product';
import { postResult } from '@/utils/dataFormat';
export default {
  props: {
    storeId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      searchCriteria: {},
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      form: {},
      parentLoading: false,
      parentOptions: []
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.loading = true;
      productVariantPage({
        name: this.searchCriteria.name ? this.searchCriteria.name : '',
        storeId: this.storeId,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        const arr = [];
        res.data.data.forEach(item => {
          const obj = {};
          Object.assign(obj, item.name);
          obj.listLeaf = item.values;
          arr.push(obj);
        });
        this.tableData = arr;
        this.total = res.data.totalCount;
        this.loading = false;
      });
    },
    searchData() {
      this.currentPage = 1;
      this.init();
    },
    getSpecParent(val) {
      if (!val) {
        return;
      }
      this.parentOptions = [];
      this.parentLoading = true;
      productVariantList({ storeId: this.storeId }).then(res => {
        this.parentLoading = false;
        const arr = [];
        res.data.forEach(item => {
          arr.push(item.name);
        });
        this.parentOptions = arr;
      });
    },
    addData() {
      // 添加规格信息
      const { name, parentId } = this.form;
      var params = {
        name,
        parentId: parentId || 0,
        isLeaf: parentId ? 1 : 0,
        storeId: this.storeId
      };
      productVariantAdd(params).then(res => {
        if (res.code === 200) {
          this.form = {};
        }
        postResult(res, this.$message, this.init);
      });
    },
    deleteItem(row) {
      this.$confirm(
        'This operation will permanently delete the specification. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          const ids = [];
          ids.push(row.id);
          if (row.isLeaf === 0) {
            // 规格名
            productVariantDeleteName(ids).then(res => {
              postResult(res, this.$message, this.init);
            });
          } else if (row.isLeaf === 1) {
            // 规格值
            productVariantDeleteVal(ids).then(res => {
              postResult(res, this.$message, this.init);
            });
          }
        })
        .catch(() => {
          this.$message.info('undeleted');
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    },
    closeVariantDialog() {
      this.$emit('closeVariantDialog');
    }
  }
};
</script>
<style lang="scss" scoped>
.area {
  display: flex;
  .areaLeft {
    flex: 1;
    width: 0;
    margin-right: 15px;
    padding-right: 15px;
    border-right: 1px solid #ddd;
    ::v-deep .el-table__expanded-cell {
      padding: 10px 50px 0px;
    }
    .tags {
      .el-tag {
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }
    .noData {
      text-align: center;
      color: #999;
    }
  }
  .areaRight {
    width: 200px;
    > p {
      line-height: 60px;
    }
  }
}
</style>
